<template>
  <a-modal
    :open="props.visible"
    :title="isEdit ? '编辑项目' : '创建项目'"
    :confirm-loading="loading"
    @ok="onSubmit"
    @cancel="onCancel"
    @update:open="(val: boolean) => emit('update:visible', val)"
    width="900px"
    :maskClosable="false"
    class="project-form-modal"
    :body-style="{ height: '65vh', padding: '0' }"
  >
    <div class="form-scroll-container">
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="项目名称" name="name">
              <a-input 
                v-model:value="formData.name" 
                placeholder="请输入项目名称"
                size="large"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="项目分组" name="groupId">
              <a-select 
                v-model:value="formData.groupId" 
                placeholder="请选择项目分组"
                size="large"
              >
                <a-select-option 
                  v-for="group in groups" 
                  :key="group.id" 
                  :value="group.id"
                >
                  {{ group.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="项目描述" name="description">
          <a-textarea 
            v-model:value="formData.description" 
            placeholder="请输入项目描述"
            :rows="3"
            size="large"
          />
        </a-form-item>
      </div>

      <!-- 环境配置 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">环境配置</h3>
          <!-- 自定义环境功能已关闭
          <a-button 
            type="dashed" 
            size="small"
            @click="addCustomEnvironment"
            class="add-custom-env-btn"
          >
            <PlusOutlined />
            添加自定义环境
          </a-button>
          -->
        </div>
        <div class="environments-grid">
          <div 
            v-for="(env, index) in formData.environments" 
            :key="index"
            class="environment-card"
            :class="`env-${env.type}`"
          >
            <div class="env-header" style="margin-bottom: 0; padding-bottom: 0; border-bottom: none;">
              <div class="env-icon">
                <EnvironmentOutlined v-if="env.type === 'development'" />
                <BugOutlined v-else-if="env.type === 'test'" />
                <RocketOutlined v-else-if="env.type === 'preview'" />
                <SafetyOutlined v-else-if="env.type === 'production'" />
                <SettingOutlined v-else-if="env.type === 'custom'" />
                <SettingOutlined v-else />
              </div>
              <div class="env-info">
                <div class="env-name">{{ getEnvironmentDisplayName(env.type) }}</div>
                <div class="env-desc">{{ getEnvironmentDescription(env.type) }}</div>
              </div>
            </div>

            <div class="env-content" style="margin-top: -5px;">
              
              <!-- 自定义环境名称输入 -->
              <!-- <a-form-item 
                v-if="env.type === 'custom'"
                label="环境名称"
                :name="['environments', index, 'name']"
                :rules="[{ required: true, message: '请输入环境名称' }]"
                class="env-name-input"
              >
                <a-input 
                  v-model:value="env.name" 
                  placeholder="请输入环境名称"
                  size="middle"
                />
              </a-form-item> -->

              <a-form-item 
                :name="['environments', index, 'type']"
                :rules="[{ required: true, message: '请选择环境类型' }]"
                class="env-type-input"
              >
                <!-- <a-select 
                  v-model:value="env.type" 
                  placeholder="环境类型"
                  size="middle"
                  :disabled="env.type !== 'custom'"
                >
                  <a-select-option value="development">开发环境</a-select-option>
                  <a-select-option value="test">测试环境</a-select-option>
                  <a-select-option value="preview">预发布环境</a-select-option>
                  <a-select-option value="production">正式环境</a-select-option>
                  <!-- 自定义环境类型已禁用
                  <a-select-option value="custom">自定义环境</a-select-option>
                  -->
                <!-- </a-select> --> 
              </a-form-item>

              <a-form-item 
                label="Host配置（可选）"
                :name="['environments', index, 'hosts']"
                class="hosts-section"
                style="margin-bottom: 0; margin-top: 0;"
              >
                <div class="textarea-container">
                  <a-textarea 
                    v-model:value="env.hostsText" 
                    :rows="4"
                    size="middle"
                    class="hosts-textarea"
                    @input="updateHostsFromText(index)"
                  />
                </div>
              </a-form-item>

              <a-form-item class="env-description">
                <div class="textarea-container">
                  <a-input 
                    v-model:value="env.description" 
                    placeholder="环境描述（可选）"
                    size="middle"
                  />
                </div>
              </a-form-item>
              
              <!-- 删除自定义环境按钮（已禁用）
              <a-form-item v-if="env.type === 'custom'" class="env-actions">
                <a-button 
                  type="text" 
                  danger 
                  size="small"
                  @click="removeCustomEnvironment(index)"
                  class="remove-custom-env-btn"
                >
                  <DeleteOutlined />
                  删除环境
                </a-button>
              </a-form-item>
              -->
            </div>
          </div>
        </div>
              </div>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue';
import { message } from 'ant-design-vue';
import { 
  EnvironmentOutlined, 
  BugOutlined, 
  RocketOutlined, 
  SafetyOutlined, 
  SettingOutlined,
  // 自定义环境功能已禁用，下面两个图标已不再使用
  // PlusOutlined,
  // DeleteOutlined
} from '@ant-design/icons-vue';
import type { FormInstance } from 'ant-design-vue';
import type { ProjectFormData, ProjectGroup, Project, EnvironmentType } from '@/types';
import { projectApi } from '@/api';

// Props
interface Props {
  visible: boolean;
  groups: ProjectGroup[];
  editProject?: Project | null;
}

const props = withDefaults(defineProps<Props>(), {
  editProject: null,
});

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  success: [];
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const loading = ref(false);

// 默认环境配置
const getDefaultEnvironments = () => [
  {
    name: '开发环境',
    type: 'development' as EnvironmentType,
    hosts: [],
    hostsText: '',
    description: '',
  },
  {
    name: '测试环境',
    type: 'test' as EnvironmentType,
    hosts: [],
    hostsText: '',
    description: '',
  },
  {
    name: '预发布环境',
    type: 'preview' as EnvironmentType,
    hosts: [],
    hostsText: '',
    description: '',
  },
  {
    name: '正式环境',
    type: 'production' as EnvironmentType,
    hosts: [],
    hostsText: '',
    description: '',
  },
];

const formData = reactive<ProjectFormData>({
  name: '',
  description: '',
  groupId: '',
  environments: getDefaultEnvironments(),
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  groupId: [{ required: true, message: '请选择项目分组', trigger: 'change' }],
  description: [{ required: false }],
};

// 计算属性
const isEdit = ref(false);

// 环境显示名称映射
const getEnvironmentDisplayName = (type: EnvironmentType) => {
  const nameMap = {
    development: '开发环境',
    test: '测试环境',
    preview: '预发布环境',
    production: '正式环境',
    custom: '自定义环境'
  };
  return nameMap[type] || type;
};

// 环境描述映射
const getEnvironmentDescription = (type: EnvironmentType) => {
  const descMap: Record<EnvironmentType, string> = {
    development: '本地开发使用',
    test: '功能测试验证',
    preview: '上线前预发布',
    production: '生产环境部署',
    custom: '自定义环境配置'
  };
  return descMap[type] || '';
};

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    resetForm();
    if (props.editProject) {
      loadEditData();
    }
  }
});

// 重置表单
const resetForm = () => {
  isEdit.value = !!props.editProject;
  Object.assign(formData, {
    name: '',
    description: '',
    groupId: '',
    environments: getDefaultEnvironments(),
  });
  
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 加载编辑数据
const loadEditData = () => {
  if (props.editProject) {
    // 合并编辑数据与默认环境，确保所有环境类型都存在
    const editEnvs = props.editProject.environments;
    const defaultEnvs = getDefaultEnvironments();
    
    // 创建环境映射
    const envMap = new Map();
    editEnvs.forEach(env => {
      envMap.set(env.type, env);
    });
    
    // 合并数据，保持默认环境顺序
    const mergedEnvironments = defaultEnvs.map(defaultEnv => {
      const editEnv = envMap.get(defaultEnv.type);
      if (editEnv) {
        return {
          name: editEnv.name,
          type: editEnv.type,
          hosts: [...editEnv.hosts],
          hostsText: editEnv.hosts.join('\n'),
          description: editEnv.description || '',
        };
      }
      return { ...defaultEnv };
    });

    Object.assign(formData, {
      name: props.editProject.name,
      description: props.editProject.description,
      groupId: props.editProject.groupId,
      environments: mergedEnvironments,
    });
  }
};

// 添加自定义环境
// 自定义环境功能已禁用
/* 
const addCustomEnvironment = () => {
  const customEnv = {
    name: '',
    type: 'custom' as EnvironmentType,
    hosts: [''],
    hostsText: '',
    description: '',
  };
  formData.environments.push(customEnv);
};
*/

// 删除自定义环境 - 已禁用
/* 
const removeCustomEnvironment = (index: number) => {
  if (formData.environments[index].type === 'custom') {
    formData.environments.splice(index, 1);
  }
};
*/

// 从文本更新Hosts数组
const updateHostsFromText = (envIndex: number) => {
  const env = formData.environments[envIndex];
  if (env.hostsText && env.hostsText.trim()) {
    // 按行分割，过滤空行，去除首尾空格
    env.hosts = env.hostsText
      .split('\n')
      .map((line: string) => line.trim())
      .filter((line: string) => line.length > 0);
  } else {
    // 允许空的host配置
    env.hosts = [];
  }
};

// 提交表单
const onSubmit = async () => {
  try {
    // 先进行自定义验证
    const validationErrors = [];
    
    // 验证自定义环境名称
    for (let i = 0; i < formData.environments.length; i++) {
      const env = formData.environments[i];
      if (env.type === 'custom' && (!env.name || env.name.trim() === '')) {
        validationErrors.push(`第${i + 1}个自定义环境名称不能为空`);
      }
    }
    
    // 如果有验证错误，显示错误信息并返回
    if (validationErrors.length > 0) {
      message.error(validationErrors.join('；'));
      return;
    }
    
    // 先更新所有环境的hosts
    formData.environments.forEach((_env, index) => {
      updateHostsFromText(index);
    });
    
    // 过滤空的host配置
    const cleanedData = {
      ...formData,
      environments: formData.environments.map(env => ({
        ...env,
        hosts: env.hosts.filter(host => host.trim()),
      })),
    };

    // 验证四个环境中至少有一个填写了Host配置
    const hasAnyHost = cleanedData.environments.some(env => env.hosts.length > 0);
    if (!hasAnyHost) {
      message.error('四个环境中至少需要填写一个Host配置');
      return;
    }

    // 通过表单验证
    await formRef.value?.validate();
    
    loading.value = true;

    if (isEdit.value && props.editProject) {
      await projectApi.update(props.editProject.id, cleanedData);
      message.success('项目更新成功');
    } else {
      await projectApi.create(cleanedData);
      message.success('项目创建成功');
    }

    emit('success');
    onCancel();
  } catch (error: any) {
    console.error('表单提交错误:', error);
    if (error.message) {
      message.error(error.message);
    } else if (error.errors) {
      // 处理表单验证错误
      const errorMessages = Object.values(error.errors).flat();
      message.error(errorMessages.join('；'));
    } else {
      message.error('操作失败，请检查表单填写是否正确');
    }
  } finally {
    loading.value = false;
  }
};

// 取消
const onCancel = () => {
  emit('update:visible', false);
};
</script>

<style scoped>
.project-form-modal :deep(.ant-modal-body) {
  height: 100%;
  padding: 0;
  overflow: hidden;
}

.project-form-modal :deep(.ant-modal-content) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.project-form-modal :deep(.ant-modal-header) {
  flex-shrink: 0;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.project-form-modal :deep(.ant-modal-body) {
  flex: 1;
  overflow: hidden;
  padding: 0;
}

.project-form-modal :deep(.ant-modal-footer) {
  flex-shrink: 0;
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

.form-scroll-container {
  height: 100%;
  padding: 24px;
  overflow-y: auto;
  overflow-x: hidden;
}

/* 自定义滚动条样式 */
.form-scroll-container::-webkit-scrollbar {
  width: 6px;
}

.form-scroll-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.form-scroll-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  transition: background 0.3s ease;
}

.form-scroll-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.form-section {
  margin-bottom: 32px;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  margin-bottom: 20px;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 40px;
  height: 2px;
  background: #1890ff;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 自定义环境按钮样式 - 已禁用
.add-custom-env-btn {
  border-style: dashed;
  border-color: #d9d9d9;
  color: #8c8c8c;
  transition: all 0.3s ease;
}

.add-custom-env-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}
*/

.environments-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
  gap: 20px;
}

/* 响应式弹窗高度和网格布局 */
@media (max-width: 1200px) {
  .project-form-modal :deep(.ant-modal-body) {
    height: 70vh !important;
  }
  
  .environments-grid {
    grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
    gap: 16px;
  }
}

@media (max-width: 768px) {
  .project-form-modal :deep(.ant-modal-body) {
    height: 75vh !important;
  }
  
  .project-form-modal :deep(.ant-modal) {
    width: 95vw !important;
    margin: 2.5vh auto;
  }
  
  .environments-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .form-scroll-container {
    padding: 16px;
  }
  
  .form-section {
    margin-bottom: 24px;
  }
  
  .section-title {
    font-size: 14px;
    margin-bottom: 16px;
  }
  
  .environment-card {
    padding: 16px;
  }
  
  .env-header {
    flex-direction: column;
    text-align: center;
    gap: 12px;
    margin-bottom: 16px;
  }
  
  .env-icon {
    margin-right: 0;
    margin-bottom: 8px;
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
  
  /* 移动端 Host 配置样式优化 */
  .hosts-section::before {
    display: none;
  }
  
  .hosts-section :deep(.ant-form-item-label > label) {
    font-size: 13px;
    letter-spacing: 0.2px;
  }
  
  .hosts-textarea {
    font-size: 12px;
    line-height: 1.5;
  }
}

.environment-card {
  border: 1px solid #f0f0f0;
  border-radius: 12px;
  padding: 12px;
  background: #ffffff;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.environment-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.environment-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #1890ff, #52c41a);
}

.env-development::before {
  background: linear-gradient(90deg, #1890ff, #40a9ff);
}

.env-test::before {
  background: linear-gradient(90deg, #faad14, #ffc53d);
}

.env-preview::before {
  background: linear-gradient(90deg, #722ed1, #b37feb);
}

.env-production::before {
  background: linear-gradient(90deg, #f5222d, #ff4d4f);
}

/* 自定义环境样式 - 已禁用
.env-custom::before {
  background: linear-gradient(90deg, #13c2c2, #36cfc9);
}
*/

.env-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid #f0f0f0;
}

.env-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background: linear-gradient(135deg, #f0f9ff, #e0f2fe);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-size: 16px;
  color: #1890ff;
}

.env-test .env-icon {
  background: linear-gradient(135deg, #fffbf0, #fefce8);
  color: #faad14;
}

.env-preview .env-icon {
  background: linear-gradient(135deg, #f9f0ff, #f4f0ff);
  color: #722ed1;
}

.env-production .env-icon {
  background: linear-gradient(135deg, #fff2f0, #fff1f0);
  color: #f5222d;
}

/* 自定义环境图标样式 - 已禁用
.env-custom .env-icon {
  background: linear-gradient(135deg, #f0fffe, #e6fffb);
  color: #13c2c2;
}
*/

.env-info {
  flex: 1;
}

.env-name {
  font-size: 14px;
  font-weight: 600;
  color: #262626;
  margin-bottom: 2px;
}

.env-desc {
  font-size: 12px;
  color: #8c8c8c;
}

.env-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.env-name-input,
.env-type-input {
  margin-bottom: 0;
}

.hosts-section {
  margin-bottom: 0 !important;
  position: relative !important;
  padding: 0 !important;
  margin: 0 !important;
}

/* 移除了 hosts-section 伪元素图标 */

.hosts-section :deep(.ant-form-item-label) {
  padding-bottom: 4px;
}

.hosts-section :deep(.ant-form-item-label > label) {
  font-weight: 600;
  color: #1f1f1f;
  font-size: 14px;
  letter-spacing: 0.3px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.hosts-section :deep(.ant-form-item-label > label)::after {
  content: none;
  display: none;
}

.hosts-textarea {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  font-size: 13px;
  line-height: 1.6;
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.hosts-textarea:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.hosts-textarea:hover {
  border-color: #40a9ff;
}

.hosts-section :deep(.ant-form-item-control) {
  position: relative;
}

.hosts-section :deep(.ant-form-item-control) {
  /* 保留样式但移除伪元素 */
  position: relative;
  border-radius: 8px;
}

.env-description {
  margin-bottom: 0;
}

.textarea-container {
  padding: 0;
  width: 100%;
  box-sizing: border-box;
}

</style>
